package com.xiaotu.test;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xiaotu.common.model.NetTVRecordsModel;
import com.xiaotu.common.util.CacheHandler;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.common.util.MathUtil;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class NetTVRecordsSpiderData {

    public static final String REGEX_INTEGER = "[一-十]+";// 整数正则

    private static final String UNIT_REGX = "千|万|亿";// 数值单位正则

    private static final BigDecimal MIN_VALUE = new BigDecimal(1000);

    private static Gson gson = new GsonBuilder().disableHtmlEscaping().create();
	
	@SuppressWarnings({ "resource", "unchecked" })
	public static void main(String[] args) {
		//注入MaoYanMovieBasicInfoService
		MaoYanMovieBasicInfoService maoYanMovieBasicInfoService = (MaoYanMovieBasicInfoService) new ClassPathXmlApplicationContext("application-context.xml").getBean("maoYanMovieBasicInfoService");

		CacheHandler cacheHandler = (CacheHandler)new ClassPathXmlApplicationContext("application-context.xml").getBean("cacheHandler");

		List<NetTVRecordsModel> recordsList = new ArrayList<NetTVRecordsModel>();

        String redisBeiAn = cacheHandler.getCache("BeiAn");
        Object object = GsonUtils.fromJson(redisBeiAn, Map.class);
        //System.out.println(object.toString());
        JSONObject searchJson = JSONObject.fromObject(object);
        JSONArray array = searchJson.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++){
            JSONObject item = array.getJSONObject(i);
            String declareNo ="0";
            String remuneration ="0";
            String cost ="0";
            if(item.containsKey("declareNo")){
                declareNo = item.getString("declareNo");
            }
            if(item.containsKey("remuneration")){
                remuneration = item.getString("remuneration");
                remuneration = remuneration.replace("￥","").replace(",","")
                        .replace(".00","").replace("元","").replace("无","0")
                .replace("，","").replace(" ","").replace("0.0","0");

                if (RegexUtils.regexMatch(REGEX_INTEGER, remuneration)
                        || remuneration.contains("百") || remuneration.contains("千")){
                    remuneration = String.valueOf(getIntegerByNumberStr(remuneration));
                }
                remuneration =  String.valueOf(unitProcess(remuneration,true));
            }
            if(item.containsKey("cost")){
                cost = item.getString("cost");
                cost = cost.replace("￥","").replace(",","").replace(".00","")
                        .replace("元","").replace("无","0").replace("，","")
                        .replace(" ","").replace("0.0","0");
                if (RegexUtils.regexMatch(REGEX_INTEGER, cost)
                        || cost.contains("百") || cost.contains("千")){
                    cost = String.valueOf(getIntegerByNumberStr(cost));
                }
                cost = String.valueOf(unitProcess(cost,true));
            }
            recordsList.add(new NetTVRecordsModel(item.getString("programName"), item.getString("cityName"),
                    item.getString("content"), cost,declareNo,
                    item.getString("insertTime"),item.getString("interval"),item.getString("isCheck").replace(".0",""),
                    item.getString("licenseNo"), item.getString("producerDept"),item.getString("programId").replace(".0",""),
                    item.getString("programLaunchCode"),item.getString("programNum"), item.getString("programSpirit"),
                    item.getString("programThemeName"), item.getString("programTypeName"),item.getString("recordEndDate"),
                    remuneration, item.getString("status"),item.getString("uploadDeptId").replace(".0",""),
                    item.getString("uploadDeptName"), item.getString("yearTypeName")));
        }

        //插入数据
        maoYanMovieBasicInfoService.saveBatchNetTVRecordS(recordsList);
	}


    /**
     * 支持到12位
     *
     * @param numberStr 中文数字
     * @return int 数字
     */
    public static int getIntegerByNumberStr(String numberStr) {

        // 返回结果
        int sum = 0;

        // null或空串直接返回
        if (numberStr == null || ("").equals(numberStr)) {
            return sum;
        }

        // 过亿的数字处理
        if (numberStr.indexOf("亿") > 0) {
            String currentNumberStr = numberStr.substring(0, numberStr.indexOf("亿"));
            int currentNumber = testA(currentNumberStr);
            sum += currentNumber * Math.pow(10, 8);
            numberStr = numberStr.substring(numberStr.indexOf("亿") + 1);
        }

        // 过万的数字处理
        if (numberStr.indexOf("万") > 0) {
            String currentNumberStr = numberStr.substring(0, numberStr.indexOf("万"));
            int currentNumber = testA(currentNumberStr);
            sum += currentNumber * Math.pow(10, 4);
            numberStr = numberStr.substring(numberStr.indexOf("万") + 1);
        }

        // 小于万的数字处理
        if (!("").equals(numberStr)) {
            int currentNumber = testA(numberStr);
            sum += currentNumber;
        }

        return sum;
    }

    /**
     * 把亿、万分开每4位一个单元，解析并获取到数据
     * @param testNumber
     * @return
     */
    public static int testA(String testNumber) {
        // 返回结果
        int sum = 0;

        // null或空串直接返回
        if(testNumber == null || ("").equals(testNumber)){
            return sum;
        }

        // 获取到千位数
        if (testNumber.indexOf("千") > 0) {
            String currentNumberStr = testNumber.substring(0, testNumber.indexOf("千"));
            sum += testB(currentNumberStr) * Math.pow(10, 3);
            testNumber = testNumber.substring(testNumber.indexOf("千") + 1);
        }

        // 获取到百位数
        if (testNumber.indexOf("百") > 0) {
            String currentNumberStr = testNumber.substring(0, testNumber.indexOf("百"));
            sum += testB(currentNumberStr) * Math.pow(10, 2);
            testNumber = testNumber.substring(testNumber.indexOf("百") + 1);
        }

        // 对于特殊情况处理 比如10-19是个数字，十五转化为一十五，然后再进行处理
        if (testNumber.indexOf("十") == 0) {
            testNumber = "一" + testNumber;
        }

        // 获取到十位数
        if (testNumber.indexOf("十") > 0) {
            String currentNumberStr = testNumber.substring(0, testNumber.indexOf("十"));
            sum += testB(currentNumberStr) * Math.pow(10, 1);
            testNumber = testNumber.substring(testNumber.indexOf("十") + 1);
        }

        // 获取到个位数
        if(!("").equals(testNumber)){
            sum += testB(testNumber.replaceAll("零",""));
        }

        return sum;
    }

    public static int testB(String replaceNumber) {
        switch (replaceNumber) {
            case "一":
                return 1;
            case "二":
                return 2;
            case "三":
                return 3;
            case "四":
                return 4;
            case "五":
                return 5;
            case "六":
                return 6;
            case "七":
                return 7;
            case "八":
                return 8;
            case "九":
                return 9;
            case "零":
                return 0;
            default:
                return 0;
        }
    }

    public static Object unitProcess(String value, boolean needThrow)
    {
        if (RegexUtils.regexMatch(RegexUtils.REGEX_E_NOTATION, value))
            return new BigDecimal(value);
        String unit = RegexUtils.regexSearch(UNIT_REGX, value);
        value = RegexUtils.replaceStr(value, UNIT_REGX, StringUtils.EMPTY);
        if(StringUtils.isBlank(value)){
            value = "0";
        }
        boolean isNumeric = RegexUtils.regexMatch(RegexUtils.REGEX_NUMBER,
                value);
        if (!isNumeric && needThrow)
            throw new IllegalArgumentException("数据类型有误，请检查后输入");
        else if (!isNumeric)
        {
            return value;
        }
        BigDecimal val = new BigDecimal(value);
        if (StringUtils.isNotEmpty(unit))
            switch (unit)
            {
                case "千":
                    val = MathUtil.mul(val, 1000);
                    break;
                case "万":
                    val = MathUtil.mul(val, 10000);
                    break;
                case "亿":
                    val = MathUtil.mul(val, 100000000);
                    break;
                default:
                    break;
            }
        if (val.compareTo(MIN_VALUE) < 0)
            return val;
        return val;
    }

    public static <T> T fromJson(String json, Class clazz)
    {
        if (StringUtils.isEmpty(json))
            return null;
        return (T) gson.fromJson(json, clazz);
    }
}
